 package test.http;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * 发出http请求
 * @author Administrator
 * @date 2018/09/21
 */
public class MakRequest {
    
    public static void main(String[] args) {
        String resultStr = null;
        try {
            resultStr = getInfoByUrl("http://127.0.0.1:8080/TestProject");
        } catch (ClientProtocolException e) {
             e.printStackTrace();
        } catch (IOException e) {
             e.printStackTrace();
        }
        System.out.println(resultStr);
    }
    
    private static String getInfoByUrl(String serviceName) throws ClientProtocolException, IOException{
        String resultStr = "";
        @SuppressWarnings("resource")
        HttpClient client = new DefaultHttpClient();
        String importType = "POST";
        serviceName = serviceName.replaceAll(" ", "%20");
        if("post".equals(importType)){
            HttpPost post = new HttpPost(serviceName);
            post.setHeader("Content-type", "application/json;charset=utf-8");
            post.setHeader("Accept", "application/json;charset=utf-8");
            StringEntity requestJson = new StringEntity(null, Charset.forName("utf-8"));
            post.setEntity(requestJson);
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            resultStr = EntityUtils.toString(entity);
        } else if("get".equals(importType)){
            HttpGet get = new HttpGet(serviceName);
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            resultStr = EntityUtils.toString(entity);
        } else if("test".equals(importType)){
//            resultStr = readToString("");
        } else {
            throw new IOException("importType错误");
        }
        return resultStr;
    }

}
